/**
* @description: 待办工单 => 执行工单
* @author: 梁蕾
* @date:
**/
<template>
  <div class="perform-task-main">
    <nav-bar class="header" back title="执行工单" @goBack="goBack"/>
    <div class="task-name">
      <div class="task-name-title">工单名称：</div>
      <div class="task-name-text">{{ currentData.hideProps.name }}</div>
    </div>
    <van-form validate-trigger="onSubmit" @submit="upload">
      <div class="main-container">
        <!-- 基本信息 -->
        <view class="base-info-container">
          <van-cell-group v-for="(item, index) in currentData.visibleProps" :key="index">
            <!-- 不可编辑框 -->
            <van-field
              v-if="item.elementType === 'TEXT'"
              :required="item.isRequired"
              readonly
              input-align="right"
              :value="item.value"
              :label="item.title"
              @click="checkInfo(item)"
            />
            <!-- 弹出筛选框 -->
            <van-field
              v-if="item.elementType === 'PICKER'"
              :required="item.isRequired"
              readonly
              clickable
              input-align="right"
              right-icon="arrow"
              :value="item.text"
              :label="item.title"
              :rules="[{ required: item.isRequired, message: '请选择' }]"
              error-message-align="right"
              placeholder="点击选择"
              @click="checkPickerList(item)"
            />
            <!-- 输入框 -->
            <van-field
              v-if="item.elementType === 'INPUT'"
              :required="item.isRequired"
              clickable
              input-align="right"
              :value="item.value"
              :label="item.title"
              placeholder="请输入"
              :type="item.type"
              :rules="[{ required: item.isRequired, message: '请填写' }]"
              error-message-align="right"
              autosize
              @input="inputBlur($event, item)"
            />
          </van-cell-group>
        </view>
        
        <!-- 执行照片 -->
        <view class="patrol-info-container">
          <view>现场照片</view>
          <van-divider dashed/>
          <div class="image-wrap">
            <div class="image-list">
              <div
                class="upload-button"
                v-for="(imgItem, index) in files"
                :style="{'background-image': `url(${imgItem.bgImg})`}"
                @click.stop="imageHandle(imgItem, index, 'CHOOSE')"
              >
                <div v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgItem, index, 'DELETE')">×</div>
                <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgItem, index, 'PREVIEW')">
              </div>
            </div>
          </div>
        </view>
        
        <!-- 备注 -->
        <view class="remark-info-container">
          <view>备注</view>
          <van-divider dashed/>
          <div class="remark-wrap">
          <textarea class="remark-text" v-model="currentData.otherProps.remark">
          </textarea>
          </div>
        </view>
  
        <!-- 执行结果 -->
        <view class="result-info-container">
          <van-cell-group v-for="(item, index) in currentData.tourInfoProps" :key="index">
            <!-- 不可编辑框 -->
            <van-field
              v-if="item.elementType === 'TEXT'"
              :required="item.isRequired"
              readonly
              input-align="right"
              :value="item.value"
              :label="item.title"
            />
          </van-cell-group>
        </view>
      </div>
      
      <van-button block native-type="submit">提交</van-button>
    </van-form>
    
    <!--选择器-->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="currentPickerList"
        @confirm="pickerConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>

    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe>
        <div v-for="(image, index) in files" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <div style="width: 100%; text-align: center;">{{ image.previewName }}</div>
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
  </div>
</template>
<script>
import navBar from "../../components/common/nav-bar";
import moment from "moment";
import axios from "axios";
import {mapGetters} from "vuex";
import { merge } from "lodash";



let infoMap = {
  hideProps: {
    "objId": "task001",    //所属工单id    //必填
    "siteid": "s001",   //所属站点
    "executerId": "2",      //执行人ID  必填      userId放进来
    "executerName": "2",    //执行人名称    必填       userName放进来
    "executerTim": "2022-12-19 00:00:00",   //执行时间 必填
    "remark": "",        //备注
    "name": ""
  },
  visibleProps: { // 显示的属性
    "type": {
      title: "检修类型",
      keys: "type",
      value: "",
      text: "",
      isRequired: true,
      elementType: "PICKER",
      optionsParams: {type: "room"}, // 获取options需要的参数
    },   //检修类型
    "category": {
      title: "检修类别",
      keys: "category",
      value: "",
      text: "",
      isRequired: true,
      elementType: "PICKER"
    },   //检修类别
    "address": {
      title: "检修工作地点",
      keys: "address",
      value: "",
      isRequired: true,
      elementType: "INPUT"
    }, //检修工作地点
    "reason": {
      title: "检修工作原因",
      keys: "reason",
      value: "",
      text: "",
      type: "textarea",
      isRequired: true,
      elementType: "INPUT",
      // optionsParams: {type: "type"}, // 获取options需要的参数
    },    //检修工作原因
    "content": {
      title: "检修工作内容",
      keys: "content",
      value: "",
      text: "",
      type: "textarea",
      isRequired: true,
      elementType: "INPUT",
    },    //检修工作内容
    "scope": {
      title: "影响范围",
      keys: "scope",
      value: "",
      text: "",
      type: "textarea",
      isRequired: true,
      elementType: "INPUT",
    },   //影响范围
  },
  tourInfoProps: { // 显示的属性。包含执行人和执行时间
    "executerName": {
      title: "执行人",
      keys: "executerName",
      value: "",
      isRequired: false,
      elementType: "TEXT"
    }, //设备名称
    "executerTim": {
      title: "执行时间",
      keys: "executerTim",
      value: "",
      isRequired: false,
      elementType: "TEXT"
    },   //所属站点名称
  },
  otherProps: {
    // 其他，如备注，照片等
    "remark": "",        //备注
  }
};

let fileTemplate = [
  {
    name: "EQUIPMENT.jpg",
    previewName: "设备照片",
    type: "EQUIPMENT",
    bgImg: require("../../static/img/bg_shebei.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "NAMEPLATE.jpg",
    previewName: "铭牌照片",
    type: "NAMEPLATE",
    bgImg: require("../../static/img/bg_mingpai.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "OTHER.jpg",
    previewName: "其他照片",
    type: "OTHER",
    bgImg: require("../../static/img/bg_qita.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
];
export default {
  name: "performTask",
  components: {navBar},
  props: {},
  data() {
    return {
      showPicker: false,
      files: fileTemplate, // 照片map
      delList: [], // 被删除的列表，需要和后台交互
      showPreview: false,
      currentData: {}, // 当前数据
      currentPickerList: [], // 当前可选的项
      currentChangeItem: "", // 当前正在修改的下拉项
    };
  },
  computed: {
    ...mapGetters(["userData"]),
  },
  watch: {},
  mounted() {
  
  },
  onLoad(options) {
    this.currentData = JSON.parse(JSON.stringify(infoMap));
    this.currentData.tourInfoProps = {
      "executerName": {
        title: "执行人",
        keys: "executerName",
        value: this.userData.userName,
        isRequired: false,
        elementType: "TEXT"
      }, //设备名称
      "executerTim": {
        title: "执行时间",
        keys: "executerTim",
        value: moment().format("YYYY-MM-DD HH:mm:ss"),
        isRequired: false,
        elementType: "TEXT"
      },   //所属站点名称
    };
    this.$api.getDetails({objId: options.objId}).then(res => {
      this.currentData.hideProps = {
        "objId": options.objId,    //所属工单id    //必填
        "siteid": "s001",   //所属站点
        "executerId": this.userData.userId,      //执行人ID  必填      userId放进来
        "remark": "2222",        //备注
        "name": res.data.name
      };
    });
  },
  // 组件销毁后清空填写内容（将填写内容初始化为空）
  beforeDestroy() {
    this.currentData = JSON.parse(JSON.stringify(infoMap));
  },
  methods: {
    goBack() {
      // 返回待办列表
      uni.navigateTo({
        url: "/pages/testProject/todoTask"
      });
    },
    checkPickerList(optionItem) {
      this.currentChangeItem = optionItem.keys;
      if (optionItem.keys === "type") {
        this.currentPickerList = [{
          text: "常规检修",
          value: "常规检修",
        }, {
          text: "重大检修",
          value: "重大检修",
        }];
      } else if (optionItem.keys === "category") {
        this.currentPickerList = [{
          text: "通信独立检修",
          value: "通信独立检修",
        }];
      }
      this.showPicker = true;
    },
    // picker确认选择(所有下拉)
    pickerConfirm(selectedOption) {
      this.currentData.visibleProps[this.currentChangeItem].text = selectedOption.text;
      this.currentData.visibleProps[this.currentChangeItem].value = selectedOption.value;
      this.showPicker = false;
    },
    // 为输入框时失去焦点采集输入值
    inputBlur(value, item) {
      this.currentChangeItem = item.keys;
      this.currentData.visibleProps[this.currentChangeItem].value = value;
    },
    updateEquipment() {
      let params = {
        objId: this.objId,
        ...this.userData,
        ...this.currentData.hideProps,
        ...Object.values(this.currentData.visibleProps).reduce((prev, item) => {
          prev[item.keys] = item.value;
          return prev;
        }, {}),
        ...Object.values(this.currentData.tourInfoProps).reduce((prev, item) => {
          prev[item.keys] = item.value;
          return prev;
        }, {}),
        ...this.currentData.otherProps
      };
      
      let requestParams = {
        params: JSON.stringify(params),
        files: this.files,
      };
      
      let param = new FormData();  // 创建form对象
      this.files.forEach((file) => {
        if (file.raw) {
          param.append('files', file.raw, file.name)
        } 
      });
      // param.append('files', this.filesRaw[0], '测试')  // 通过append向form对象添加数据
      param.append("params", requestParams.params); // 添加form表单中其他数据
      let config = {
        headers: {"Content-Type": "multipart/form-data",Authorization: uni.getStorageSync('token') || ''}
      };
      // 添加请求头
      axios.post("/ap/txksh/kosinManage/rest/api/taskjx/updateTask", param, config)
        .then(response => {
          uni.navigateTo({
            url: `/pages/testProject/todoTask`
          });
        });
    },
    imageHandle (imgItem, imgIndex, handleType) {
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgItem, imgIndex);
      } else if (handleType === 'PREVIEW') {
        this.showPreview = true;
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          message: `是否确认删除${imgItem.previewName}`
        })
          .then(() => {
            this.$set(this.files, imgIndex, {
              ...this.files[imgIndex],
              raw: null,
              img: ''
            })
            this.delList.includes(imgItem.type) ? null: this.delList.push(imgItem.type);
              console.log(this.delList, "delete")

          })
          .catch(() => {
            // on cancel
          })
      }
    },
    choosePhoto(imgItem, imgIndex) {
      let _this = this;
      wx.chooseImage({
        count: 3,
        sourceType: ["camera"],
        success: (chooseImageRes) => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
                const localData = res.localData;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                    //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                    imageBase64 = localData;
                } else {
                    //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                    //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                    imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
                }
                
                _this.$set(_this.files, imgIndex, merge(_this.files[imgIndex], {
                   raw: _this.h5_url_to_blob(imageBase64),
                   img: imageBase64
                }));

                
                if (_this.delList.includes(imgItem.type)) {
                  _this.delList = _this.delList.filter(item => {
                    if (item === imgItem.type) {
                      return false;
                    }
                    
                    return true;
                  });
                }
            }
          });
        },
        fail: (error) => {
          console.log(error);
        }
      });
    },
    h5_url_to_blob(url) {
      let arr = url.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    upload() {
      this.updateEquipment();
    }
  }
};
</script>
<style scoped lang="scss">
.perform-task-main {
  width: 100vw;
  height: 100vh;
  background: #F2F6FA;
  overflow: hidden;

  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .van-swipe {
      width: 100%;
      height: 60%;
    }
    img {
      height: 90%;
    }
  }
  
  .task-name {
    width: 100vw;
    height: px2vh(140);
    background-color: #ffffff;
    box-sizing: border-box;
    padding: 0 px2vw(30) 0 px2vw(49);
    display: flex;
    justify-content: start;
    align-items: center;
    
    .task-name-title {
      width: 20vw;
      font-size: px2vw(42);
    }
    
    .task-name-text {
      //width: px2vw(220);
      flex: 1;
      height: px2vh(80);
      border-radius: px2vw(40);
      font-size: px2vw(42);
      display: flex;
      //justify-content: center;
      align-items: center;
      font-weight: bold;
    }
  }
  
  .main-container {
    height: calc(100vh - #{px2vh(573)});
    padding: px2vh(30) px2vw(30) 0 px2vw(30);
    overflow: auto;
    
    .base-info-container, .result-info-container {
      margin-bottom: px2vw(30);
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      
      /deep/ .van-field__body {
        textarea {
          color: red;
        }
      }
    }
    
    .result-info-container {
      margin: px2vh(30) 0 0 0;
    }
    
    .remark-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      margin-top: px2vh(30);
      
      .remark-wrap {
        background-color: #FAFAFA;
        padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
        border-radius: px2vw(20);
        
        .remark-text {
          height: px2vh(150);
        }
      }
    }
    
    .patrol-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      
      /deep/ .van-radio {
        margin-right: px2vw(139.5)
      }
      
      .image-list {
        width: 100%;
        display: flex;
        .upload-button {
          width: px2vw(215);
          height: px2vw(215);
          background-size: cover;
          margin-right: px2vw(40);
          position: relative;
          .delete-icon {
            position: absolute;
            top: px2vw(-20);
            right: px2vw(-20);
            width: px2vw(40);
            height: px2vw(40);
            background-color: rgba(0, 0, 0, 0.7);
            border-radius: 50%;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }
  
  .van-button {
    margin: px2vh(60) auto;
    width: calc(100vw - #{px2vw(60)});
    height: px2vh(120);
    color: #fff;
    background-color: #417ADC;
    border: 1px solid #417ADC;
    border-radius: px2vh(60);
  }
}
</style>